<!--
 * @Description: 个人设置
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-06-10 14:25:34
 * @LastEditTime: 2021-09-28 10:57:09
 * @LastEditors: 0001101008/HuYuxi
-->
<template>
  <div class="page-content user">
    <div class="header">
      <div class="left-wrap">
        <h2>{{date}}，{{info.cnRoleName}}</h2>
        <h2>{{info.dgName}}</h2>
        <h2>{{info.userlabel}}</h2>
      </div>
      <div class="right-wrap">
        <img src="/static/images/info-bg.png" />
      </div>
    </div>
    <div class="info">
      <h1 class="title">基本设置</h1>
      <el-form
        :model="form"
        class="form"
        :rules="rules"
        ref="ruleForm"
        label-width="86px"
        label-position="top"
      >
        <el-form-item label="显示名" prop="userlabel">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-input v-model="form.userlabel" :disabled="!isEdit" maxlength="50" />
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-input type="password" v-model="form.password" maxlength="14" :disabled="!isEdit" />
          </el-col>
        </el-form-item>
        <el-form-item label="确认密码" prop="chkpassword">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-input
              type="password"
              v-model="form.chkpassword"
              maxlength="14"
              :disabled="!isEdit"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="API令牌" prop="apiToken">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-input v-model="form.apiToken" :disabled="!isEdit" readonly>
              <el-button slot="prepend" @click="getAPIToken">Token</el-button>
              <el-button slot="append" icon="el-icon-document-copy" @click="copyToken"></el-button>
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 90px" @click="edit">{{isEdit ? '保存' : '编辑'}}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import crypto from '@/utils/crypto';
export default {
  data () {
    // 验证密码
    let valPwd = (rule, value, callback) => {
      let _this = this;
      if (value === '' || value === null || value === undefined) {
        callback();
      } else {
        let pwd = _this.form.password;
        // 正则
        let i = /[0-9]+/;
        let str = /[A-Za-z]/;
        let spec = /[,.<>{}~!@#$%^&*]/;
        if (pwd.length > 5 && pwd.length < 15) {
          if (!i.test(pwd)) {
            callback(new Error('密码不符合规范，必须包含数字'));
          }
          if (!str.test(pwd)) {
            callback(new Error('密码不符合规范，必须包含字母'));
          }
          if (!spec.test(pwd)) {
            callback(new Error('密码不符合规范，必须包含 !@#$%^&* 其中一个或多个!'));
          } else {
            callback();
          }
        } else {
          callback(new Error('密码长度不符合规范，6-14位'));
        }
      }
    };
    let chkPwd = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback();
      }
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      isEdit: false,
      date: '',
      info: {},
      form: {
        userlabel: null,
        password: null,
        chkpassword: null,
        apiToken: null
      },
      rules: {
        userlabel: [
          { required: true, message: '请输入显示名', trigger: 'blur' },
          { pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '输入不合法，包含特殊符合！', trigger: 'blur' }
        ],
        password: [
          { validator: valPwd, trigger: 'blur' }
        ],
        chkpassword: [
          { validator: chkPwd, trigger: 'blur' }
        ]
      }
    };
  },
  mounted () {
    let _this = this;
    _this.$nextTick(() => {
      _this.getDate();
      _this.getInfo();
    });
  },
  methods: {
    // 时间过滤
    getDate () {
      const d = new Date();
      const h = d.getHours();
      let date;
      if (h >= 6 && h < 9) {
        date = '早上好';
      } else if (h >= 9 && h < 11) {
        date = '上午好';
      } else if (h >= 11 && h < 13) {
        date = '中午好';
      } else if (h >= 13 && h < 18) {
        date = '下午好';
      } else if (h >= 18 && h < 24) {
        date = '晚上好';
      } else if (h >= 0 && h < 6) {
        date = '很晚了，早点睡';
      }
      this.date = date;
    },
    // 获取用户基本信息
    getInfo () {
      let _this = this;
      _this.$http.get({
        url: '/api/gateway/user/self'
      }).then(res => {
        _this.info = res;
        _this.form.userlabel = res.userlabel;
      });
    },
    // 重新生成api令牌
    getAPIToken () {
      this.$http.get({
        url: '/api/gateway/user/token'
      }).then(res => {
        this.form.apiToken = res;
      });
    },
    // 复制
    copyToken () {
      let copyipt = document.createElement('input');
      copyipt.setAttribute('value', this.form.apiToken);
      document.body.appendChild(copyipt);
      copyipt.select();
      document.execCommand('copy');
      document.body.removeChild(copyipt);
      this.$message.success({
        message: '复制成功',
        duration: 1500
      });
    },
    edit () {
      let _this = this;
      if (_this.isEdit) {
        _this.$refs['ruleForm'].validate(async (valid) => {
          if (valid) {
            _this.isEdit = !_this.isEdit;
            let params = {};
            // 显示名
            if (_this.form.userlabel !== _this.info.userlabel) {
              params.userlabel = _this.form.userlabel;
            }
            if (_this.form.password !== '' && _this.form.password !== null && _this.form.password !== undefined) {
              // 密码
              const key = await crypto.getKey();
              const pwd = crypto.encrypt(crypto.hash(_this.form.password), key);
              params.password = pwd;
            }
            if (_this.form.apiToken !== '' && _this.form.apiToken !== null && _this.form.apiToken !== undefined) {
              // API令牌
              params.apiToken = _this.form.apiToken;
            }
            _this.$http.put({
              url: '/api/gateway/user/self',
              data: params
            }).then(res => {
              if (_this.form.password !== '' && _this.form.password !== null && _this.form.password !== undefined) {
                _this.$message.success('设置成功！');
                document.getElementsByTagName('html')[0].removeAttribute('class'); // 移除暗黑主题
                this.$store.dispatch('user/setLoginStatus', false);
                this.$router.push('/login');
              } else {
                _this.$message.success('设置成功！');
                _this.getInfo();
              }
            });
          } else {
            _this.$message.error('请检查必填项！');
          }
        });
      } else {
        _this.isEdit = !_this.isEdit;
      }
    }
  }
};
</script>

<style lang='scss' scoped>
.page-content {
  width: 100%;
  height: 100%;
  padding: 0 !important;
  background: transparent !important;

  .header {
    background: #fff;
    padding: 30px 40px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;

    .left-wrap {
      .avatar {
        width: 110px;
        height: 110px;
        object-fit: cover;
        border-radius: 50%;
      }

      h2 {
        font-size: 30px;
        margin-top: 20px;
        font-weight: 500;
      }

      p {
        color: #9ca3ae;
        font-size: 14px;
        margin-top: 20px;
        display: none;
      }

      .task {
        margin-top: 30px;
        display: flex;
        align-items: center;

        span {
          color: #9ca3ae;
          font-size: 14px;
          margin-right: 30px;
          margin-left: 8px;
        }
      }
    }

    .right-wrap {
      display: flex;
      align-items: center;

      img {
        width: 230px;
      }
    }
  }

  .info {
    margin-top: 15px;
    background: #fff;

    .title {
      font-size: 22px;
      font-weight: 500;
      padding: 15px 40px;
      border-bottom: 1px solid #eee;
    }

    .form {
      padding: 30px 40px;
      box-sizing: border-box;
    }
  }
}

@media only screen and (max-width: $device-ipad) {
  .page-content {
    .header {
      padding: 20px 20px;

      .left-wrap {
        .avatar {
          width: 90px;
          height: 90px;
        }

        h2 {
          font-size: 20px;
          margin-top: 20px;
        }

        .task {
          margin-top: 15px;

          .icon {
            width: 2.8em;
            height: 2.8em;
            vertical-align: -0.15em;
          }

          span {
            font-size: 15px;
          }
        }
      }

      .right-wrap {
        display: flex;
        align-items: center;

        img {
          display: none;
        }
      }
    }

    .info {
      .title {
        font-size: 18px;
        padding: 15px 20px;
      }

      .form {
        padding: 30px 20px;
      }
    }
  }
}
</style>